<?php
//后台控制器类
namespace Admin\Controller;
use Think\Model\RelationModel;
use Think\Upload;
use Org\Util\Page;
use Org\Yike\Rights;
class CommonController extends BaseController{
    protected $_name = '';
    protected $menuid = 0;
    protected $list_relation = false;
    protected $_ajaxedit = 0;
    protected $_exclude = '';
    protected $_data = array();
    protected $addAll = false;
    public function _initialize() {
		parent::_initialize();
        if(C('ATUO_AUTH_RIGHTS')){
          $this->check(C('ATUO_AUTH_RIGHTS'));
        }
        $this->_name = CONTROLLER_NAME;
        $this->menuid = I('request.menuid',0,'intval');
        if ($this->menuid) {
            $sub_menu = D('menu')->sub_menu($this->menuid, $this->big_menu);
            $selected = '';
            foreach ($sub_menu as $key=>$val) {
                $sub_menu[$key]['class'] = '';
                if (CONTROLLER_NAME == $val['module_name'] && ACTION_NAME == $val['action_name'] && strpos(__SELF__, $val['data'])) {
                    $sub_menu[$key]['class'] = $selected = 'on';
                }
            }
            if (empty($selected)) {
                foreach ($sub_menu as $key=>$val) {
                    if (CONTROLLER_NAME == $val['module_name'] && ACTION_NAME == $val['action_name']) {
                        $sub_menu[$key]['class'] = 'on';
                        break;
                    }
                }
            }
            $this->assign('sub_menu', $sub_menu);
        }
        $this->assign('menuid', $this->menuid);
    }

    /**
     * 列表页面
     */
    public function index() {
        $map = $this->_search();
        $mod = D($this->_name);
        !empty($mod) && $this->_list($mod, $map);
        $this->options = $this->check();
        $this->display();
    }

    /**
     * 添加
     */
    public function add(){
        $mod = D($this->_name);
        if (IS_POST) {
            if (false === $data = $mod->create()) {
                IS_AJAX && $this->ajaxReturn(0, $mod->getError());
                $this->error($mod->getError());
            }
            if (method_exists($this, '_before_insert')) {
                $data = $this->_before_insert($data);
            }
            if($this->addAll ? $mod->addAll($data) :$mod->add($data)){
                if( method_exists($this, '_after_insert')){
                    $id = $mod->getLastInsID();
                    $this->_after_insert($id);
                }
                IS_AJAX && $this->ajaxReturn(1, L('operation_success'), '', 'add');
                $this->success(L('operation_success'));
            } else {
                IS_AJAX && $this->ajaxReturn(0, L('operation_failure'));
                $this->error(L('operation_failure'));
            }
        } else {
            $this->assign('open_validator', true);
            //户型数据
            $house_type = M ('used_type')->where ('status=1')->select ();
            $this->assign ('house_type', $house_type);
            if (IS_AJAX) {
                $response = $this->fetch();
                $this->ajaxReturn(1, '', $response);
            } else {
				$this->display();
            }
        }
    }

    /**
     * 修改
     */
    public function edit(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        if (IS_POST) {
            if (false === $data = $mod->create()) {
                IS_AJAX && $this->ajaxReturn(0, $mod->getError());
                $this->error($mod->getError());
            }
            if (method_exists($this, '_before_update')) {
                $data = $this->_before_update($data);
            }
            if (false !== $mod->save($data)) {
                if( method_exists($this, '_after_update')){
                    $id = $data['id'];
                    $this->_after_update($id);
                }
                IS_AJAX && $this->ajaxReturn(1, L('operation_success'), '', 'edit');
                $this->success(L('operation_success'));
            } else {
                IS_AJAX && $this->ajaxReturn(0, L('operation_failure'));
                $this->error(L('operation_failure'));
            }
        } else {
            $id = I($pk);
            $info = $mod->find($id);
            $this->assign('info', $info);
            $this->assign('open_validator', true);
            if (IS_AJAX) {
                $response = $this->fetch();
                $this->ajaxReturn(1, '', $response);
            } else {
                $this->display();
            }
        }
    }

    /**
     * ajax修改单个字段值
     */
    public function ajax_edit()
    {
        //AJAX修改数据
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $id = I($pk);
        $field = I('get.field');
        $val = I('get.val');
        //允许异步修改的字段列表  放模型里面去 TODO
        $mod->where(array($pk=>$id))->setField($field, $val);
        $this->ajaxReturn(1);
    }

    /**
     * 删除
     */
    public function delete(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = trim(I($pk), ',');
        if ($ids) {
            if (false !== $mod->delete($ids)) {
                IS_AJAX && $this->ajaxReturn(1, L('operation_success'));
                $this->success(L('operation_success'));
            } else {
                IS_AJAX && $this->ajaxReturn(0, L('operation_failure'));
                $this->error(L('operation_failure'));
            }
        } else {
            IS_AJAX && $this->ajaxReturn(0, L('illegal_parameters'));
            $this->error(L('illegal_parameters'));
        }
    }

    /**
     * 获取请求参数生成条件数组
     */
    protected function _search() {
        //生成查询条件
        $mod = D($this->_name);
        $map = array();
        foreach ($mod->getDbFields() as $key => $val) {
            if (substr($key, 0, 1) == '_') {
                continue;
            }
            if (I($val)) {
                $map[$val] = I($val);
            }
        }
        return $map;
    }

    /**
     * 列表处理
     *
     * @param obj $model  实例化后的模型
     * @param array $map  条件数据
     * @param string $sort_by  排序字段
     * @param string $order_by  排序方法
     * @param string $field_list 显示字段
     * @param intval $pagesize 每页数据行数
     */
    protected function _list($model, $map = array(), $sort_by='', $order_by='', $field_list='*', $pagesize=20){
        //排序
        $mod_pk = $model->getPk();
        if (I("sort")) {
            $sort = I("sort");
        } else if (!empty($sort_by)) {
            $sort = $sort_by;
        } else if ($this->sort) {
            $sort = $this->sort;
        } else {
            $sort = $mod_pk;
        }
        if (I("order")) {
            $order = I("order");
        } else if (!empty($order_by)) {
            $order = $order_by;
        } else if ($this->order) {
            $order = $this->order;
        } else {
            $order = 'DESC';
        }
        //如果需要分页
        if ($pagesize) {
           $count = $model->where($map)->count($mod_pk);
		  // import('ORG.Util.Page');
           $pager = new Page($count, $pagesize);
        }
        $select = $model->field($field_list)->where($map)->order($sort . ' ' . $order);
        $this->list_relation && $select->relation(true);//关联表
        if ($pagesize) {
            $select->limit($pager->firstRow.','.$pager->listRows);
            $page = $pager->show();
            $this->assign("page", $page);
        }
        $list = $select->select();
        $this->assign('list', $list);
        $this->assign('list_table', true);
    }
    
	//修改配置文件
    protected function update_config($new_config, $config_file = '') {
        !is_file($config_file) && $config_file = CONF_PATH . '/config.php';
        if (is_writable($config_file)) {
            $config = require $config_file;
            $config = array_merge($config, $new_config);
            file_put_contents($config_file, "<?php \nreturn " . stripslashes(var_export($config, true)) . ";", LOCK_EX);
            @unlink(RUNTIME_FILE);
            return true;
        } else {
            return false;
        }
    }
    public function ajaxGetchilds() {
        $id = I('id');
        $menuid = I('get.menuid',0,'int');
        $map = array('pid'=>$id);
        if($menuid){
            $map['menuid'] = $menuid;
        }
        $return = M('linkmenu')->field('id,name')->where($map)->select();
        if ($return) {
            $this->ajaxReturn(1, L('operation_success'), $return);
        } else {
            $this->ajaxReturn(0, L('operation_failure'));
        }
    }
    protected function _insertPic($data){
        //上传图片
        if (!empty($_FILES['img']['name'])) {
            $img = $this->_upload();
            $data['img'] = $img['img']['savepath'].$img['img']['savename'];
        }
        if(isset($_POST['pic']) && !empty($_POST['pic'])) {
            $pic = array();
            $images = $_POST['pic'];
            foreach ($images['pic'] as $key => $v) {
                $pic[] = array('img' => $v, 'alt' => $images['alt'][$key]);
            }
            $data['file'] = !empty($pic) ? json_encode($pic) : '';
        }
        return $data;
    }

    protected function _updatePic($data,$field='id'){
        $mod = M($this->_name);
        $img = $mod->where(array($field=>$data['id']))->find();
        $old_img = $img['img'];
        if (!empty($_FILES['img']['name'])) {
            //删除原图
            if($old_img){
                @unlink('.'.$old_img);
            }
                $img = $this->_upload();
                $data['img'] = $img['img']['savepath'].$img['img']['savename'];
        }

        if(isset($_POST['pic']) && !empty($_POST['pic'])){
            $pic = array();
            $images = $_POST['pic'];
            foreach($images['pic'] as $key=>$v){
                $pic[] = array('img'=>$v,'alt'=>$images['alt'][$key]);
            }
            $data['file'] = !empty($pic) ? json_encode($pic) : '';
        }
        return $data;
    }
    /**
     * 上传文件
     */
    protected function _upload($dir='',$w='') {
        if(!$dir) $dir = (CONTROLLER_NAME == 'Ad' or CONTROLLER_NAME == 'Advert') ? 'FangCms' : CONTROLLER_NAME;
        $savepath = $dir.'/';
        $upload = new Upload();
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     $savepath; // 设置附件上传（子）目录
        $upload->saveName = array('uniqid',date("His"));
        $upload->subName  = array('date','Ymd');
        if(!file_exists($upload->rootPath.$savepath)){
            mkdir($upload->rootPath.$savepath);
        }
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            $img = '.'.$info['img']['savepath'].$info['img']['savename'];
            //加水印
            $rootpath = $_SERVER['DOCUMENT_ROOT'];
            if(C('WATER_FUNTION')==1 && !$w){
                $imgObj = new \Think\Image();
                $imgObj->open($img);
                $waterpos = C('WATER_POS');
                $watercom = C('WATER_COMPRESSION');
                switch(C('WATER_FILE_TYPE')){
                    case 1:
                        $waterimg = $rootpath.str_replace('./','/',C('WATER_IMAGE'));
                        $imgObj->water($waterimg,$waterpos,$watercom);
                        break;
                    case 2:
                        $waterfont = $rootpath.str_replace('./','/',C('WATER_FONTFILE'));
                        $imgObj->text(C('WATER_TEXT'),$waterfont,C('WATER_FONTSIZE'),C('WATER_FONTCOLOR'),$waterpos,0,C('WATER_ANGLE'));
                        break;
                }
                $imgObj->save($img);
            }
            return $info;
        }
    }

    //加水印
    public function imgWatermark($img){
        $rootpath = $_SERVER['DOCUMENT_ROOT'];
        if(C('WATER_FUNTION')==1){
            $imgObj = new \Think\Image();
            $imgObj->open($img);
            $waterpos = C('WATER_POS');
            $watercom = C('WATER_COMPRESSION');
            switch(C('WATER_FILE_TYPE')){
                case 1:
                    $waterimg = $rootpath.str_replace('./','/',C('WATER_IMAGE'));
                    $imgObj->water($waterimg,$waterpos,$watercom);
                    break;
                case 2:
                    $waterfont = $rootpath.str_replace('./','/',C('WATER_FONTFILE'));
                    $imgObj->text(C('WATER_TEXT'),$waterfont,C('WATER_FONTSIZE'),C('WATER_FONTCOLOR'),$waterpos,0,C('WATER_ANGLE'));
                    break;
            }
            $imgObj->save($img);
        }
    }

    //ajax上传图片
    public function ajax_upload_img() {
        //$type = I('type', 'trim', 'img');
        if (!empty($_FILES['img']['name'])) {
            $dir = '';
            $result = $this->_upload($dir,$w=1);
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $savename = $result['img']['savepath'].$result['img']['savename'];
                $this->ajaxReturn(1, L('operation_success'), $savename);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }
    /**
     * AJAX返回数据标准
     *
     * @param int $status
     * @param string $msg
     * @param mixed $data
     * @param string $dialog
     */
    protected function ajaxReturn($status=1, $msg='', $data='', $dialog='') {
        parent::ajaxReturn(array(
            'status' => $status,
            'msg' => $msg,
            'data' => $data,
            'dialog' => $dialog,
        ),'json');
    }

    /**
     * @param bool $isauto 是否是自动验证 默认为手动验证
     * @param array $data = array(
     *                              'c'=>要验证的控制器名称
     *                              'a'=>要验证的方法名称
     *                              'str'=>返回的字符串 (其中url请用%s替代 不设置将返回空)
     *                              'replace'=>可选 （如果木有权限的时候返回的提示字符 默认返回无权限）
     *                              'param'=>url参数变量用@id@（固定格式）替代 该参数将会附到url链接中
     *                             )
     * @exclude string; 排除默认列表中的值
     * @param string $returntype 返回的类型 默认返回字符串 取值str|arr arr返回数组
     * @return array|string
     */
    protected function check($isauto=false,$returntype='str'){
       //如果是自动验证
       $return = '';
       $editstr = '<a href="%s">编辑</a>';
       $editajax = '<a data-height="300" data-width="500" data-id="edit" data-uri="%s" data-title="编辑 - %s" class="J_showdialog" href="javascript:;">编辑</a>';
       $default = array(
            'edit'    => array(
                'c' => CONTROLLER_NAME,
                'a' => 'edit',
                'str'    => '',
                'param' => array('id'=>'@id@'),
                'isajax' => $this->_ajaxedit,
                'replace'=> ''
            ),
            'delete' => array(
                'c'   => CONTROLLER_NAME,
                'a'   => 'delete',
                'param' => array('id'=>'@id@'),
                'str' => '<a data-uri="%s" data-msg="确定要删除 %s 吗？" data-acttype="ajax" class="J_confirmurl" href="javascript:void(0);">删除</a>',
                'isajax'  => 1,
                'replace' => ''
            )
        );
        $optionarr = array('edit','delete');
        if(!empty($this->_exclude) && in_array($this->_exclude,$optionarr)){
            unset($default[$this->_exclude]);
        }
       if($isauto){
           $c = CONTROLLER_NAME;
           $a = ACTION_NAME;
           if(!Rights::check($c,$a)){
               IS_AJAX ? $this->ajaxReturn(0,'无权限操作','无权限操作') : $this->error('无权限操作');
           }
       }else{
           if(empty($this->_data)){
               $data = $default;
           }else{
               $data = array_merge($this->_data,$default);
           }
           //一维数组的处理方法 直接返回处理后的字符串
          /* if(count($data)==count($data, 1)){
               $c = $data['c'];
               $a = $data['a'];
               $str   = isset($data['str']) && !empty($data['str']) ? $data['str'] : '';
               $replace = isset($data['replace']) && !empty($data['replace']) ? $data['replace'] : '无权限';
               if(Rights::check($c,$a)){
                   $return = sprintf($str,urldecode(U($c.'/'.$a,$param)));
               }else{
                   $return = '<span class="disabled">'.$replace.'</span>';
               }
           }else{*/
               //二维数组的处理方法
               foreach($data as $k=>$v){
                   $c = $v['c'];
                   $a = $v['a'];
                   $param = $v['param'];
                   if(!isset($param['menuid'])){
                       $param['menuid'] = '@menuid@';
                   }
                   $str   = $k=='edit' ? ($v['isajax']==1 ? $editajax : $editstr) : $v['str'];
                   $replace = isset($v['replace']) && !empty($v['replace']) ? $v['replace'] : '无权限';
                   if(Rights::check($c,$a)){
                       $return[] = sprintf($str,urldecode(U($c.'/'.$a,$param)),'@name@');
                   }else{
                       $return[] = '<span class="disabled-link">'.$replace.'</span>';
                   }
               }
               if($returntype=='str'){
                   $return = implode(' | ',$return);
               }
           return $return;
       }

   }

    public function fileEncode(){
        $domain = $_SERVER['HTTP_HOST'];
        if(strpos($domain,'www.')!==FALSE){
            $domain = str_replace('www.','',$domain);
        }
        $code =  F('Licence');
        $exclude =array('localhost','127.0.0.1');
        if(in_array($domain,$exclude)){
            return true;
        }
        if(!$code){
            $curl = new \Org\Yike\Curl();
            $url = "http://www.fangcms.com/checkright.html";
            $arr['domain'] = $domain;
           // $url .= '?domain='.$domain;echo $domain;
            $data = $curl->post($url,$arr);
            $decode = think_decrypt($data);
            F('Licence',$data);
        }else{
            $decode = think_decrypt($code);
        }
        $rightdomain = explode('|',$decode);
        if($domain != $rightdomain[0]){
           $this->error('请到官网购买正版!','http://www.fangcms.com');
        }
    }
}
?>